import json
from fastapi import Request, Depends, Query, HTTPException
from fastapi.security import SecurityScopes
from typing import Union
from core.response import notAuthenticated
from core.utils import en_password_md5
from core.storage import RedisStorage
from config.app import get_config


async def check_client(req: Request, client: str = Query(None)):
    clientId: str = req.headers.get("App-Client-Id") if client is None else client
    # 检查客户端是否OK
    if clientId == 'e5cd7e4891bf95d1d19206ce24a7b32e':
        return clientId
    else:
        return 'e5cd7e4891bf95d1d19206ce24a7b32e'
        # notAuthenticated()


async def global_filter(req: Request, security_scopes: SecurityScopes, access_token: Union[str, None] = None, clientId=Depends(check_client)) -> Union[bool]:
    config = get_config()
    if req.url.path in config.SECURITY_EXCLUDES:
        # 放行API不做权限认证
        return True
    else:
        rs = await check_permission(req, access_token)
        if rs == False:
            notAuthenticated()
        # print("--------- global filter ---------")
    # 校验客户端


async def check_permission(req: Request, access_token: Union[str, None] = None) -> bool:
    token = req.headers.get("Authorization") if access_token is None else access_token

    config = get_config()

    if req.url.path in config.SECURITY_EXCLUDES:
        return True

    if token is None:
        return False

    key = config.TOKEN_PREFIX + en_password_md5(token, config.TOKEN_SECRET)

    info = await RedisStorage.get_cache_object(req.app, key)

    if info is None:
        return False

    info = json.loads(info)
    if info is None:
        return False

    req.app.state.user = info

    # 通过token查询用户
    # 用户基本信息
    # 用户的角色
    # 用户的功能权限
    # 用户的部门
    # 如果查不到提示token无效

    return True
